import React, {PureComponent} from 'react';
import {Button, DeviceEventEmitter, StyleSheet, View, ToastAndroid, Text} from 'react-native';
import Download from './Download';
import AnimatedBar from './anmiatedBar';

/**
 * @FileName: DownloadDemo
 * @Author: mazaiting
 * @Date: 2018/7/13
 * @Description:
 */
class DownloadDemo extends PureComponent {
	constructor(props) {
		super(props);
		this.state = {
			progress: 0
		}
	}
	
	render() {
		return (
			<View style={styles.container}>
				<Button
					style={{marginTop: 20, marginBottom: 20}}
					title='下载'
					onPress= {() => this.download()}
				/>
				<View style={{width: 600, height: 30}}/>
				<Button
					style={{marginTop: 20, marginBottom: 20}}
					title='取消'
					onPress= {() => this.cancel()}
				/>
				<View style={{flex: 1, flexDirection:'column', alignItems: 'center', width: 500, height: 100}}>
					<Text
						style={{alignItems: 'center', height: 50, width: 500, color: '#ff0000'}}
						// title={"正在下载中" + this.state.progress * 100 + "%"}
					>正在下载中{parseInt(this.state.progress * 100)}%</Text>
					<AnimatedBar
						progress={this.state.progress}
						borderRadius={10}
						height={2}
					/>
				</View>
			</View>
		)
	}
	
	/**
	 * 下载
	 */
	download() {
		// ToastAndroid.show("mazaiting", ToastAndroid.SHORT);
		// 参数1：文件名称
		// 参数2：成功回调
		// 参数3：失败回调
		Download.downloadApk(
			'huihe.apk',
			(msg) => {
				ToastAndroid.show("下载成功", ToastAndroid.SHORT);
			},
			(error) => {
				// ToastAndroid.show(error, ToastAndroid.SHORT);
				ToastAndroid.show("下载失败", ToastAndroid.SHORT);
			}
			);
	}
	
	/**
	 * 取消下载
	 */
	cancel() {
		Download.cancel();
	}
	
	componentDidMount() {
		let that = this;
		DeviceEventEmitter.addListener('downloadApk', function (params) {
			// 将字符串解析为JSON数据
			let json = JSON.stringify(params);
			// 将JSON数据解析为对象
			let data = JSON.parse(json);
			// 获取进度值
			let progress = data.progress / 100;
			that.updateProgress(progress);
			if (progress === 1) {
				ToastAndroid.show('下载完成!', ToastAndroid.SHORT);
			}
		});
	}
	
	/**
	 * 更新进度
	 * @param progress 进度，百分比
	 */
	updateProgress(progress) {
		
		ToastAndroid.show(progress+"", ToastAndroid.SHORT);
		this.setState({
			progress: progress
		})
	}
}

/**
 * 样式属性
 */
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#DDD'
	}
});

/**
 * 导出当前Module
 */
module.exports = DownloadDemo;